package com.yehuishou.realm;


import java.util.Collection;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yehuishou.pojo.HUser;
import com.yehuishou.pojo.Permission;
import com.yehuishou.service.HUserService;
import com.yehuishou.service.PermissionService;

/**
 * 
 * @author zxb
 *
 */

@Service
public class YehuishouRealm extends AuthorizingRealm {

	@Autowired
	private HUserService huserService;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private SessionDAO sessionDAO;
	
	// 授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		//根据当前登录的用户查询权限
		Subject subject = SecurityUtils.getSubject();
		HUser huser = (HUser) subject.getPrincipal();
		//调用业务层查询权限
		List<Permission> list = permissionService.findByHUser(huser);
		for (Permission permission : list) {
			authorizationInfo.addStringPermission(permission.getKeyword());
		}
		return authorizationInfo;
	}

	// 认证..
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// 转换token
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

		// 根据用户名 查询 用户信息
		HUser huser = huserService.findByUname(usernamePasswordToken.getUsername());
		
		if (huser == null) {
			// 用户名不存在
			// 参数一： 期望登录后，保存在Subject中信息
			// 参数二： 如果返回为null 说明用户不存在，报用户名
			// 参数三 ：realm名称
			return null;
		} else {
			//判断用户登录没有
			Collection<Session> sessions = sessionDAO.getActiveSessions();
			if(sessions != null && sessions.size()>0){
				for (Session session : sessions) {
					HUser hu = (HUser) session.getAttribute("huser");
					if(hu != null && hu.getUname().equals(huser.getUname())) {
						//用户已经登录
						session.setTimeout(0);  //这里就把session清除，
					}
				}
			}
			// 用户名存在
			// 当返回用户密码时，securityManager安全管理器，自动比较返回密码和用户输入密码是否一致
			// 如果密码一致 登录成功， 如果密码不一致 报密码错误异常
			return new SimpleAuthenticationInfo(huser, huser.getUpassword(), getName());
		}

	}

}
